package com.github.m6d21.sso.business.controller.user;

import static com.github.m6d21.sso.support.enums.StatusCode.SERVER_ERROR;

import com.github.m6d21.sso.common.util.EmptyUtil;
import com.github.m6d21.sso.model.user.entity.User;
import com.github.m6d21.sso.model.user.qo.UserQO;
import com.github.m6d21.sso.model.user.vo.UserVO;
import com.github.m6d21.sso.service.user.IUserService;
import com.github.m6d21.sso.support.annotation.RequestArrayParam;
import com.github.m6d21.sso.support.annotation.RequestDateParam;
import com.github.m6d21.sso.support.enums.StatusCode;
import com.github.m6d21.sso.support.model.Response;
import com.github.m6d21.sso.support.session.SsoSessionHolder;
import com.github.m6d21.sso.support.util.ResponseUtil;
import com.github.m6d21.sso.support.validator.password.Password;
import com.github.m6d21.sso.support.validator.password.PasswordConstant;
import com.github.m6d21.sso.support.validator.password.PasswordConstant.Type;
import com.github.m6d21.sso.support.validator.phone.Phone;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 *<p>
 *账号api
 *</p>
 *
 * @author liuyang
 * @date 2018-12-07 Fri 13:27:00
 * @since 1.0.0
 */
@Api(value = "user", description = "账号api")
@Validated
@RestController
@RequestMapping("/web/user")
public class UserController {

    @Resource
    private IUserService userService;

    @ApiOperation(value = "根据用户名密码获取账户信息", httpMethod = "GET")
    @GetMapping("/find/name/passwd")
    @ResponseBody
    public Response<List<User>> findByUsernameAndPassword
        (@NotNull(message = "用户名不能为空") @RequestParam("username") String username,
            @NotNull(message = "密码不能是空") @RequestParam("password") String password) {
        return ResponseUtil.success(userService.findByUsernameAndPassword(username, password));
    }

    @ApiOperation(value = "保存账号信息", httpMethod = "POST")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "username", value = "用户名", paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "displayName", value = "昵称", paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "password", value = "密码", paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "phone", value = "手机号", paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "email", value = "邮箱", paramType = "query", dataType = "string")})
    @PostMapping("/save")
    @ResponseBody
    public Response<Integer> saveUser(
        @NotBlank(message = "用户名不能为空") @RequestParam("username") String username,
        @NotBlank(message = "昵称不能为空") @RequestParam("displayName") String displayName,
        @NotBlank(message = "密码不能为空") @Password(message = PasswordConstant.SIMPLE_TIP, type = Type.SIMPLE) @RequestParam("password") String password,
        @NotBlank(message = "邮箱不能为空") @Email(message = "邮箱格式不正确") @RequestParam("email") String email,
        @NotBlank(message = "手机号不能为空") @Phone @RequestParam("phone") String phone) {

        User user = new User();
        user.setUsername(username);
        user.setDisplayName(displayName);
        user.setPassword(password);
        user.setEmail(email);
        user.setPhone(phone);
        user.setOperator(SsoSessionHolder.getDisplayName());
        userService.saveUser(user);
        return ResponseUtil.success(user.getId());
    }

    @ApiOperation(value = "修改账号信息", httpMethod = "POST")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "username", value = "用户名", paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "displayName", value = "昵称", paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "password", value = "密码", paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "phone", value = "手机号", paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "email", value = "邮箱", paramType = "query", dataType = "string")})

    @PostMapping("/modify")
    @ResponseBody
    public Response<Integer> modifyUser(
        @NotNull(message = "用户ID不能为空") @RequestParam("id") Integer id,
        @RequestParam(value = "username", required = false) String username,
        @RequestParam(value = "displayName", required = false) String displayName,
        @Password(message = PasswordConstant.SIMPLE_TIP, type = Type.SIMPLE) @RequestParam(value = "password", required = false) String password,
        @Email(message = "邮箱格式不正确") @RequestParam(value = "email", required = false) String email,
        @Phone @RequestParam("phone") String phone) {

        User user = new User();
        user.setId(id);
        user.setUsername(username);
        user.setDisplayName(displayName);
        user.setPassword(password);
        user.setEmail(email);
        user.setPhone(phone);
        user.setOperator(SsoSessionHolder.getDisplayName());
        userService.modifyUserById(user);
        return ResponseUtil.success(user.getId());
    }

    @ApiOperation(value = "查询用户", httpMethod = "GET")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNo", value = "页码(当前页)", paramType = "query", dataType = "int"),
        @ApiImplicitParam(name = "pageSize", value = "分页大小", paramType = "query", dataType = "int"),
        @ApiImplicitParam(name = "username", value = "用户名", paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "displayName", value = "昵称", paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "phone", value = "手机号", paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "email", value = "邮箱", paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "startDate", value = "创建时间", paramType = "query", dataType = "date"),
        @ApiImplicitParam(name = "endDate", value = "创建时间", paramType = "query", dataType = "date")})
    @GetMapping(value = "/query")
    @ResponseBody
    public Response<PageInfo<User>> query
        (
            @RequestParam(value = "pageNo", required = false) Integer pageNo,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "displayName", required = false) String displayName,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "email", required = false) String email,
            @RequestDateParam(value = "startDate") Date startDate,
            @RequestDateParam(value = "endDate") Date endDate) {
        UserQO userQO = new UserQO();
        userQO.setUsername(EmptyUtil.ifBlankToNull(username));
        userQO.setDisplayName(EmptyUtil.ifBlankToNull(displayName));
        userQO.setPhone(EmptyUtil.ifBlankToNull(phone));
        userQO.setEmail(EmptyUtil.ifBlankToNull(email));
        userQO.setStartDate(startDate);
        userQO.setEndDate(endDate);

        return ResponseUtil.success(userService.queryByPage(pageNo, pageSize, userQO));
    }


    @ApiOperation(value = "根据token获取用户信息", httpMethod = "GET")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "token", value = "token", paramType = "query", dataType = "string")
    })
    @GetMapping("/get/by/token")
    @ResponseBody
    public Response getUserByToken
        (@NotBlank(message = "token不能为空") @RequestParam("token") String token) {
        User user = userService.getUserByToken(token);
        UserVO userVO = null;
        if (user != null) {
            userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
        } else {
            return ResponseUtil.fail(SERVER_ERROR.getCode(), "无效的token: " + token);
        }
        return ResponseUtil.success(userVO);
    }

    @ApiOperation(value = "获取当前用户信息", httpMethod = "GET")
    @GetMapping("/get/current")
    @ResponseBody
    public Response getCurrentUser() {
        User user = userService.getCurrentUser();
        UserVO userVO = null;
        if (user != null) {
            userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
        } else {
            return ResponseUtil.fail(SERVER_ERROR.getCode(), "尚未登录");
        }
        return ResponseUtil.success(userVO);
    }

    @ApiOperation(value = "查询用户是否存在", httpMethod = "GET")
    @ApiImplicitParam(name = "username", value = "用户名", paramType = "query", dataType = "string")
    @GetMapping("/exist/username")
    @ResponseBody
    public Response existByUsername(@RequestParam(value = "username", required = false) String username) {
        Boolean exist = userService.exist(username);
        Map<String, Boolean> data = new HashMap<>();
        data.put("exist", exist);
        return ResponseUtil.success(data);
    }


    @ApiOperation(value = "根据用户ID删除用户", httpMethod = "POST")
    @ApiImplicitParam(name = "id", value = "用户ID", paramType = "query", dataType = "int")
    @PostMapping("/delete/id")
    @ResponseBody
    public Response deleteUserById
        (@NotNull(message = "用户ID不能为空") @RequestParam("id") Integer id) {
        Boolean success = userService.deleteUserById(id);
        if (!success) {
            return ResponseUtil.fail(StatusCode.FAIL.getCode(), "删除失败");
        }
        return ResponseUtil.success();
    }

    @ApiOperation(value = "根据用户ID批量删除用户", httpMethod = "POST")
    @ApiImplicitParam(name = "ids", value = "用户ID数组", paramType = "query", dataType = "array")
    @PostMapping("/delete/ids")
    @ResponseBody
    public Response deleteUserByIds
        (@NotNull(message = "用户ID不能为空") @RequestArrayParam(value = "ids", type = Integer.class) Integer[] ids) {
        Boolean success = userService.deleteUserByIds(Lists.newArrayList(ids));
        if (!success) {
            return ResponseUtil.fail(StatusCode.FAIL.getCode(), "删除失败");
        }
        return ResponseUtil.success();
    }
}
